// pages/selfAssessment/uploadVideo/index.js
const api = require("../../../config/api")
const request = require("../../../utils/request")
import VODUpload from '../../../utils/aliyun-upload-sdk-1.0.1.min.js'
const base64 = require('../../../utils/base64_vadio.js')
const {
	parse,
	getTodayDate
} = require("../../../utils/util")
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		file: {
			coverUrl: "http://tmp/qC1NBrJ1hukIe5516d0050b91d1abda7259a9a1daa75.jpg",
			url: "http://tmp/p3eMURMhjSyS3d5c1a1afce1f280e1fbafc1c26070b8.mp4"
		},
		duration: ""
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		wx.enableAlertBeforeUnload({
			message: '视频正在上传，是否要放弃上传'
		})
		const data = parse(options.data)
		const today = getTodayDate()
		this.setData({
			file: data.file,
			duration: data.duration,
			id: data.id,
			today: today.year + '-' + today.month + '-' + today.day
		})
	},
	saveBtn() {
		const uploader = this.data.uploader;
		const userData = '{"Vod":{}}'
		const file = this.data.file
		uploader.addFile(file, null, null, null, userData)
		this.data.uploader.startUpload();
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {
		const that = this;
		let FileName
		let uploader = new VODUpload({
			timeout: 60000,
			region: "cn-shanghai",
			// 添加文件成功
			addFileSuccess: function(uploadInfo) {
				console.log("addFileSuccess" + JSON.stringify(uploadInfo))
			},
			// 开始上传
			onUploadstarted: function(uploadInfo) {
				that.getVideoVoucher(uploadInfo,uploader)
			},
			// 文件上传成功
			onUploadSucceed: function(uploadInfo) {
				console.log(JSON.stringify(uploadInfo))
				console.log('文件上传成功!')
			},
			// 文件上传失败
			onUploadFailed: function(uploadInfo, code, message) {
				uploader.stopUpload();
			},
			// 取消文件上传
			onUploadCanceled: function(uploadInfo, code, message) {
				uploader.stopUpload();
			},
			// 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
			onUploadProgress: function(uploadInfo, totalSize, progress) {
				let files;
				if (uploadInfo.isImage) {
					files = that.data.images;
				} else {
					files = that.data.videos;
				}

				files.forEach((file, idx) => {
					if (file.url === uploadInfo.url) {
						file.progress = progress;
						if (uploadInfo.isImage) {
							that.setData({
								images: files
							})
						} else {
							that.setData({
								videos: files
							})
						}
					}
				})
				let progressPercent = Math.ceil(progress * 100)
			},
			// 上传凭证超时
			onUploadTokenExpired: function(uploadInfo) {},
			// 全部文件上传结束
			onUploadEnd: function(uploadInfo) {
				that.savaVideo()

				console.log("文件上传完毕 onUploadEnd: uploaded all the files")
			}
		});

		this.setData({
			uploader: uploader,
			FileName: FileName
		});
	},
	// 获取上传凭证
	getVideoVoucher: async function(uploadInfo,uploader) {

		console.log('文件开始上传...');
		const url = uploadInfo.url
		const paramas = {
			title: url,
			fileName: url
		}
		const res = await request.get(api.videoVoucher, paramas)
		if (res.httpStatus === 200) {
			const akInfo = res.data;
			const adress = parse(base64.decode(res.data.UploadAddress));
			this.setData({
				adress: adress,
				aliyunVideoId: akInfo
			})
			uploader.setUploadAuthAndAddress(uploadInfo, akInfo
				.UploadAuth, akInfo.UploadAddress, akInfo
				.VideoId);

			wx.showLoading({
				title: '上传中…'
			})
		}
	},
	// 保存视频信息
	savaVideo: async function() {
		const data = this.data
		const userId = wx.getStorageSync('userId')
		const paramas = {
			aliyunVideoId: data.aliyunVideoId.VideoId,
			patientId: data.id,
			userId: userId,
			uploadVoucher: 'uploadVoucher',
			videoUrl: data.adress.FileName,
			videoLength: data.duration
		}
		const res = await request.post(api.saveVideo, paramas)
		if (res.httpStatus === 200) {
			wx.hideLoading()
			wx.navigateTo({
				url: '/pages/selfAssessment/uploadVideo/success'
			})
		}
		// this.chooseVideo()
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		wx.disableAlertBeforeUnload()
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
